﻿using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using Isuka.Automation;

namespace Isuka.Excel
{
    /// <summary>
    /// Excel アプリケーション
    /// </summary>
    public sealed class XApplication
        : AutomationRootObject
    {
        /// <summary>
        /// Excel Workbooks オブジェクト
        /// </summary>
        readonly XWorkbooks workbooks;

        /// <summary>
        /// コンストラクター
        /// </summary>
        public XApplication()
            : base("Excel.Application")
        {
            workbooks = new XWorkbooks(this, Object.Workbooks);
        }

        public XWorkbook ActiveBook
        {
            get
            {
                return new XWorkbook(this, Object.ActiveWorkbook);
            }
        }

        public XWorksheet ActiveSheet
        {
            get
            {
                return new XWorksheet(ActiveBook, Object.ActiveSheet);
            }
        }

        public bool CutCopyMode
        {
            get
            {
                VerifyNotDisposed();
                return Object.CutCopyMode;
            }
            set
            {
                VerifyNotDisposed();
                Object.CutCopyMode = value;
            }
        }

        public bool Visible
        {
            get
            {
                VerifyNotDisposed();
                return Object.Visible;
            }
            set
            {
                VerifyNotDisposed();
                Object.Visible = value;
            }
        }

        public XWorkbooks Workbooks
        {
            get
            {
                Contract.Ensures(Contract.Result<XWorkbooks>() != null);
                VerifyNotDisposed();
                return workbooks;
            }
        }

        #region AutomationContainer メンバー

        protected override void ReleaseObject(object obj)
        {
            // Excel アプリケーションを終了させる
            Object.Quit();
            base.ReleaseObject(obj);
        }

        #endregion

        #region ContractInvariantMethod

        [ContractInvariantMethod]
        [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Required for code contracts.")]
        [DebuggerStepThrough]
        void ObjectInvariant()
        {
            Contract.Invariant(workbooks != null);
        }

        #endregion
    }
}
